package com.example.yiqiuser.service.impl;

import com.example.yiqiuser.dao.TuserDao;
import com.example.yiqiuser.entity.Tuser;
import com.example.yiqiuser.exception.BusinessException;
import com.example.yiqiuser.service.TuserService;
import com.example.yiqiuser.util.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * @program: yiqiuser
 * @description:
 * @author: 诸葛龙辰
 * @create: 2023-04-05 20:35
 * @version:
 **/
@Service
public class TuserServiceImpl implements TuserService {
    //依赖注入，依赖dao
    @Resource
    private TuserDao tuserDao;

    @Override
    public Tuser checkTuer(Tuser tuser) {
        List<Tuser> userList = tuserDao.checkUser(tuser);
        if (userList != null && userList.size() > 0) {
            return userList.get(0);
        }
        return null;
    }

    @Override
    public PageInfo queryPage(Page<Tuser> page) {
        PageHelper.startPage(page.getPageNo(), page.getPageSize());
        return new PageInfo(tuserDao.queryPage(page.getData()));

    }

    @Override
    public int add(Tuser tuser) {
        //加密加盐设置
        //获取原来的密码
        String oldPassword = tuser.getPassword();
        //生成盐值
        String salt = UUID.randomUUID().toString();
        //生成加密密码
        Sha512Hash sha512Hash = new Sha512Hash(oldPassword,salt,1024);
        //设置加密过后的密码
        tuser.setPassword(sha512Hash.toString());
        //盐值
        tuser.setSalt(salt);
        return tuserDao.add(tuser);
    }

    @Override
    public int delete(Integer id) {
        return tuserDao.delete(id);
    }

    @Override
    public int update(Tuser tuser) {
        return tuserDao.update(tuser);
    }

    /**
     * 查询单个
     * @param tuser
     * @return
     */
    @Override
    public Tuser checkUsers(Tuser tuser) {
        Tuser tuser1 = tuserDao.checkUsers(tuser);
        if (tuser1==null){
            throw new BusinessException("账号不存在");
        }
        if (!tuser.getPassword().equals(tuser1.getPassword())){
            throw new BusinessException("密码错误");
        }
        return tuser1;
    }

    /**
     * 验证手机号是否存在
     *
     * @param tuser
     * @return
     */
    @Override
    public Tuser checkMobile(Tuser tuser) {
        List<Tuser> userList = tuserDao.checkMobile(tuser);
        if (userList != null && userList.size() > 0) {
            return userList.get(0);
        }
        return null;
    }

    /**
     * 根据编号查询
     *
     * @param id
     * @return
     */
    @Override
    public Tuser queryById(Integer id) {
        return  tuserDao.queryById(id);
    }
}
